
const Router = require('koa-router');
const multer = require('koa-multer');
const { getDB } = require('../modules/db');

const router = new Router();

// 处理文件上传的中间件
const storage = multer.diskStorage({
    // 文件保存路径
    destination: function(req, file, cb) {
        // 指定上传文件的存储目录
        cb(null, 'public/upload');
    },
    // 修改文件名称
    filename: function(req, file, cb) {
        //  获取后缀名
        const ext = file.originalname.split('.');
        // 指定上传文件的文件名
        cb(null, Date.now() + '.' + ext[ext.length - 1])
    },
});

//加载配置
const upload = multer({
    storage: storage
});

router.post('/upload', upload.single('file'), async (ctx, next) => {

    // 获取上传文件的信息
    const { file } = ctx.req;
    // 额外参数
    const { name } = ctx.req.body;
    // 数据库交互
    const { find, close } = getDB();

    const con = find();
    // file 是avatar文件的信息
    // ctx.req.body 文本域的数据 如果存在
    const baseUrl = `http://localhost:3000/upload/${file.filename}`;

    try {

        const [rows] = await con.execute(
            'INSERT INTO `files` (`name`, `url`, `count`) VALUE (?, ?, ?)',
            [name, baseUrl, 1]
        );

        if (rows.affectedRows === 0) {
            ctx.body = {
                success: false,
                code: 400,
                msg: "上传失败"
            }
            return;
        }

        ctx.body = {
            success: true,
            code: 200,
            msg: "上传成功"
        }
        return;
    } catch (error) {
        ctx.body = {
            success: false,
            code: 500,
            msg: "服务器错误",
            error
        }
    }
    finally {
        // 释放连接
        close();
    }
});

// 文件列表
router.get('/files', async (ctx, next) => {
    const { pageNo, pageSize } = ctx.query;

    // 数据库交互
    const { find, close } = getDB();

    const con = find();

    try {
        // 限制条数
        const limit = pageSize;

        // 开始位置
        const offset = (pageNo - 1) * pageSize;

        const [rows] = await con.query(
            'SELECT * FROM `files` ORDER BY `id` DESC LIMIT ? OFFSET ?',
            [Number(limit), offset]
        );

        ctx.body = {
            success: true,
            code: 200,
            msg: "获取成功",
            data: rows,
            count: rows.length
        }
    }
    catch (error) {
        ctx.body = {
            success: false,
            code: 500,
            msg: "服务器错误",
            error
        }
    }
    finally {
        // 释放连接
        close();
    }
});


module.exports = router;